Page({
  onLoad() {
    this.getHouse()
  },
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    currentDate: Date.now(),
    houseId: '',
    mobile: '',
    name: '',
    gender: 1,
    houseList: [
      { name: '北京西三旗花园1号楼 101' },
      { name: '北京东村家园3号楼 302' },
      { name: '北京育新花园3号楼 703' },
      { name: '北京天通苑北苑8号楼 403' },
    ],
  },
  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  //查询审核通过的房屋
  async getHouse() {
    const { data } = await wx.http.get('/house')
    this.setData({
      houseList: data
    })
  },
  //选择房屋信息
  selectHouse(e) {
    console.log(e);
    const { name: houseInfo, id: houseId } = e.detail
    this.setData({
      houseInfo, houseId
    })
  },
  //选择日期
  onConfirm(e) {
    const time = wx.utils.formatTime(e.detail)
    console.log(time);
    this.setData({
      dateLayerVisible: false,
      visitDate: time
    })
  },
  //校验选择房屋信息
  checkSelectHouse() {
    const vaild = Boolean(this.data.houseId)
    if (!vaild) wx.utils.toast('请选择房屋信息')
    return vaild
  },
  //校验姓名
  cheackName() {
    const reg = /^(?:[\u4e00-\u9fa5·]{2,16})$/
    const vaild = reg.test(this.data.name.trim())
    if (!vaild) wx.utils.toast('请输入2~16位中文姓名')
    return vaild
  },
  //校验手机号
  checkMobile() {
    const reg = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/
    const vaild = reg.test(this.data.mobile)
    if (!vaild) wx.utils.toast('请输入合法的手机号')
    return vaild
  },
  //校验预约日期
  checkDate() {
    const reg = /^\d{4}[-|/]\d{2}[-|/]\d{2}$/
    const vaild = reg.test(this.data.visitDate)
    if (!vaild) wx.utils.toast('请选择访问日期')
    return vaild
  },
  //确认提交
  async onSubmit() {
    if (!this.checkSelectHouse()) return
    if (!this.cheackName()) return
    if (!this.checkMobile()) return
    if (!this.checkDate()) return
    const { houseId, name, gender, mobile, visitDate } = this.data
    const { data: { id } } = await wx.http.post('/visitor', { houseId, name, gender, mobile, visitDate })
    wx.utils.toast('填写访客信息成功')
    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index?id=' + id
    })
  },
})
